package com.yuhanginfo.modules.web.web;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yuhanginfo.common.web.BaseController;
import com.yuhanginfo.modules.web.util.WebUserUtils;
import com.yuhanginfo.modules.web.entity.WebAddress;
import com.yuhanginfo.modules.web.entity.WebFreeWaybill;
import com.yuhanginfo.modules.web.entity.WebGoods;
import com.yuhanginfo.modules.web.entity.WebGoodsCombDetail;
import com.yuhanginfo.modules.web.entity.WebGoodsCombStore;
import com.yuhanginfo.modules.web.entity.WebGoodsCombo;
import com.yuhanginfo.modules.web.entity.WebInvoiceInfo;
import com.yuhanginfo.modules.web.entity.WebOrders;
import com.yuhanginfo.modules.web.entity.WebOrdersDetail;
import com.yuhanginfo.modules.web.entity.WebStore;
import com.yuhanginfo.modules.web.entity.WebYongUser;
import com.yuhanginfo.modules.web.service.AddressService;
import com.yuhanginfo.modules.web.service.CustomerHistoryViewService;
import com.yuhanginfo.modules.web.service.GoodsListService;
import com.yuhanginfo.modules.web.service.OrderService;
import com.yuhanginfo.modules.web.service.WebClassService;
import com.yuhanginfo.modules.web.service.WebFreeWaybillService;
import com.yuhanginfo.modules.web.service.WebGoodsCombDetailService;
import com.yuhanginfo.modules.web.service.WebGoodsCombStoreService;
import com.yuhanginfo.modules.web.service.WebGoodsComboService;
import com.yuhanginfo.modules.web.service.WebGoodsService;
import com.yuhanginfo.modules.web.service.WebInvoiceInfoService;
import com.yuhanginfo.modules.web.service.WebOrdersDetailService;
import com.yuhanginfo.modules.web.service.WebStoreService;

/**
 * 套餐Controller
 * @author lvls
 * @version 2017-10-30
 */
@Controller
@RequestMapping(value = "${frontPath}/goodsComb")
public class WebGoodsCombController extends BaseController {

	@Autowired
	private WebClassService webClassService;
	@Autowired
	private WebGoodsComboService webGoodsComboService;
	@Autowired
	private WebGoodsCombDetailService webGoodsComboDetailService;
	@Autowired
	private WebGoodsCombStoreService webGoodsCombStoreService;
	@Autowired
	private WebStoreService webStoreService;
	@Autowired
	private AddressService addressService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private WebOrdersDetailService webOrderDetailService;
	@Autowired
	private WebFreeWaybillService freeWaybillService;
	@Autowired
	private WebInvoiceInfoService webInvoiceInfoService;
	@Autowired
	private GoodsListService goodsListService;
	@Autowired
	private CustomerHistoryViewService customerService;
	@Autowired
	private WebGoodsService webGoodsService;
	
	
	@RequestMapping(value = "list")
	public String list(WebGoodsCombo WebGoodsComb, Model model) {
		WebYongUser yongUser = WebUserUtils.getYongUser();
		String userId;
		model.addAttribute("allClassesList",webClassService.getAllClasses());
		if("1".equals(yongUser.getUserType())){
			userId = null;
		}else{
			userId = yongUser.getId();
		}
		model.addAttribute("allGoodsComboList",webGoodsComboService.selectByUserId(userId));
		return "modules/web/goodsCombo/goodsComboList";
	}
	
	@RequestMapping(value = "detail")
	public String detail(WebGoodsCombo WebGoodsComb, Model model) {
		WebGoodsCombo getWebGoodsComb = webGoodsComboService.get(WebGoodsComb);
		List<WebStore> stores = webGoodsCombStoreService.getStoreByGoodsCombo(getWebGoodsComb);
		WebStore firstStore = new WebStore();
		if(stores!=null){
			firstStore = stores.get(0);
		}
		List<WebGoodsCombDetail> webGoodsCombDetails = webGoodsComboDetailService.selectByGoodsComboId(getWebGoodsComb.getId());
		BigDecimal oldPrice = BigDecimal.valueOf(0, 2);
		for (WebGoodsCombDetail webGoodsCombDetail : webGoodsCombDetails) {
			oldPrice = oldPrice.add(webGoodsCombDetail.getOldPrice().multiply(BigDecimal.valueOf(webGoodsCombDetail.getNum())));
		}
		model.addAttribute("webGoodsCombDetails",webGoodsCombDetails);
		getWebGoodsComb.setOldPrice(oldPrice);
		model.addAttribute("allClassesList",webClassService.getAllClasses());
		model.addAttribute("firstStore",firstStore);
		model.addAttribute("WebGoodsComb",getWebGoodsComb);
		return "modules/web/goodsCombo/goodsComboDetail";
	}
	
	@RequestMapping(value = "toGoodsComboOrder")
	public String toGoodsComboOrder(WebGoodsCombo WebGoodsComb, Model model) {
		WebYongUser yongUser = WebUserUtils.getYongUser();
		WebGoodsComb = webGoodsComboService.get(WebGoodsComb);
		List<WebStore> stores = webGoodsCombStoreService.getStoreByGoodsCombo(WebGoodsComb);
		if(yongUser.getId()==null){
			return "modules/web/webLogin";//到登陆页面
		}
		List<WebAddress> addressList = addressService.selectByUserId(Integer.parseInt(yongUser.getId()));
		WebAddress defAddress = null;
		for (WebAddress address : addressList) {
			if("1".equals(address.getIsDef())){
				defAddress = address;
			}
		}
		List<WebGoodsCombDetail> webGoodsCombDetails = webGoodsComboDetailService.selectByGoodsComboId(WebGoodsComb.getId());
		model.addAttribute("allClassesList",webClassService.getAllClasses());
		model.addAttribute("webStore",new WebStore());
		model.addAttribute("webStores",stores);
		model.addAttribute("addressList", addressList);
		model.addAttribute("defAddress", defAddress);
		model.addAttribute("webGoodsCombDetails",webGoodsCombDetails);
		model.addAttribute("WebGoodsComb",WebGoodsComb);
		if("1".equals(yongUser.getUserType())){
			return "modules/web/goodsCombo/commonGoodsComboConfirmOrder";
		}else{
			return "modules/web/goodsCombo/vipGoodsComboConfirmOrder";
		}
	}
	
	/**
	 * 生成会员用户订单
	 */
	@RequestMapping(value = "vipGoodsComboConfirmOrder")
	public String vipGoodsComboConfirmOrder(WebOrders Order,
			String goodsComboId,
			Integer goodsComboNum,
			String goodsComboStoreCode,
			String provinceId) {
		WebYongUser yongUser = WebUserUtils.getYongUser();
		if(yongUser.getId()==null){
			return "modules/web/webLogin";//到登陆页面
		}
		WebGoodsCombo webGoodsCombo = webGoodsComboService.get(goodsComboId);
		WebGoodsCombStore combStore = new WebGoodsCombStore();
		combStore.setGoodsCombCode(webGoodsCombo.getCode());
		combStore.setStoreCode(goodsComboStoreCode);
		List<WebGoodsCombStore> list = webGoodsCombStoreService.selectByGoodsComboCodeAndStoreCode(combStore);
		if(list.isEmpty()){
			return "modules/web/Order/createOrderFailed";
		}
		Order.setPayType("0");
		insertOrder(Order, goodsComboNum, provinceId, yongUser, goodsComboId, goodsComboStoreCode);
		return "redirect:"+ frontPath +"/payment/goPaymentShow?orderCode="+Order.getCode();
	}
	
	
	/**
	 * 生成普通用户订单
	 */
	@RequestMapping(value = "commmonGoodsComboConfirmOrder")
	public String commmonGoodsComboConfirmOrder(WebOrders Order,
			WebInvoiceInfo webInvoiceInfo,
			String goodsComboId,
			Integer goodsComboNum,
			String goodsComboStoreCode,
			String provinceId) {
		WebYongUser yongUser = WebUserUtils.getYongUser();
		if(yongUser.getId()==null){
			return "modules/web/webLogin";//到登陆页面
		}
		WebGoodsCombo webGoodsCombo = webGoodsComboService.get(goodsComboId);
		WebGoodsCombStore combStore = new WebGoodsCombStore();
		combStore.setGoodsCombCode(webGoodsCombo.getCode());
		combStore.setStoreCode(goodsComboStoreCode);
		List<WebGoodsCombStore> list = webGoodsCombStoreService.selectByGoodsComboCodeAndStoreCode(combStore);
		if(list.isEmpty()){
			return "modules/web/Order/createOrderFailed";
		}
		Order.setPayType("1");
		insertOrder(Order, goodsComboNum, provinceId, yongUser, goodsComboId, goodsComboStoreCode);
		if("1".equals(Order.getIsInvoice())){
			webInvoiceInfo.setReceiveAddress(webInvoiceInfo.getInvoiceReceiveAddress());
			webInvoiceInfo.setReceiveName(webInvoiceInfo.getInvoiceReceiveName());
			webInvoiceInfo.setReceivePhone(webInvoiceInfo.getInvoiceReceivePhone());
			webInvoiceInfo.setMoney(Order.getMoney());
			webInvoiceInfo.setOrderId(Order.getId());
			webInvoiceInfo.setOrdersCode(Order.getCode());
			webInvoiceInfo.setUserId(Order.getUserId());
			webInvoiceInfo.setStatus(0);
			webInvoiceInfo.setPayType(1);
			webInvoiceInfoService.save(webInvoiceInfo);
		}
		return "redirect:"+ frontPath +"/payment/goPaymentShow?orderCode="+Order.getCode();
	}
	/**
	 * 套餐详情里面进入商品详情
	 * 可显示未上架，已上架，已下架商品
	 */
	@RequestMapping(value = "goodsComboToList")
	public String goodsComboToList(String goodsComboId,String goodsCode,String storeCode,String useIp,HttpServletRequest request, HttpServletResponse response, Model model) {
		WebYongUser yongUser=WebUserUtils.getYongUser();
		//删除历史浏览表脏数据
		customerService.deleteRub();
		customerService.save(goodsCode,storeCode,useIp);
		model.addAttribute("user",yongUser);
		WebGoods webGoods = webGoodsService.getByCode(goodsCode);
		Map<String,String> params=new HashMap<String, String>();
		params.put("goodsCode", goodsCode);
		params.put("useIp", useIp);
		if(webGoods.getStatus()==0){
			model.addAttribute("goodsDetail", goodsListService.goodsComboToList(params));
		}else{
			List<WebStore> stores = webStoreService.selectByGoods(goodsCode);
			params.put("storeCode", stores.get(0).getCode());
			model.addAttribute("goodsDetail", goodsListService.getGoodsByCode(params));
		}
		model.addAttribute("allClassesList",webClassService.getAllClasses());
		model.addAttribute("isGoodsCombo",1);
		model.addAttribute("historyList",customerService.getHistoryGoodsByIp(useIp));
		return "modules/web/goodsCombo/ComboToGgoodsDetail";
	}
	
	@RequestMapping(value = "getStoreByCode")
	@ResponseBody
	public WebStore getStoreByCode(WebStore store,HttpServletRequest request, HttpServletResponse response, Model model) {
		return webStoreService.getByCode(store.getCode());
	}
	
	private void insertOrder(WebOrders Order, Integer goodsComboNum, String provinceId, WebYongUser yongUser,
			String goodsComboId, String goodsComboStoreCode) {
		WebGoodsCombo webGoodsCombo = webGoodsComboService.get(goodsComboId);
		WebStore WebStore = webStoreService.getByCode(goodsComboStoreCode);
		//是否包邮
		BigDecimal price = webGoodsCombo.getPrice();
		BigDecimal sumPrice = price.multiply(BigDecimal.valueOf(goodsComboNum));
		WebFreeWaybill freeWaybill = new WebFreeWaybill();
		freeWaybill.setReceiveAreaId(provinceId);
		freeWaybill.setSendAreaId(WebStore.getClassify());
		WebFreeWaybill webFreeWaybillByArea = freeWaybillService.getWebFreeWaybillByArea(freeWaybill);
		Order.setMoney(sumPrice);
		Order.setBuyStoreCode(WebStore.getCode());
		Order.setBuyStoreName(WebStore.getCnName());
		Order.setOrderType(2);
		Order.setUserId(Integer.parseInt(yongUser.getId()));
		String orderCode = getOrderReturnCode();
		Order.setCode(orderCode);
		Order.setIsHistory("0");
		Order.setState("1");
		BigDecimal tranfee = BigDecimal.valueOf(0.00);
		if(webFreeWaybillByArea!=null){
			//价格低于包邮价格
			if(sumPrice.compareTo(webFreeWaybillByArea.getMoney())==-1){
				//运费
				tranfee = sumPrice.multiply(BigDecimal.valueOf(0.1));
				Order.setPayMoney(sumPrice.add(tranfee));
			}else{
				Order.setPayMoney(sumPrice);
			}
		}else{
			//运费
			tranfee = sumPrice.multiply(BigDecimal.valueOf(0.1));
			Order.setPayMoney(sumPrice.add(tranfee));
		}
		Order.setFreight(tranfee);
		//新增订单详情
		WebOrdersDetail webOrderDetail = new WebOrdersDetail();
		webOrderDetail.setOrdersCode(orderCode);
		webOrderDetail.setGoodsCode(webGoodsCombo.getCode());
		webOrderDetail.setGoodsCnName(webGoodsCombo.getName());
		webOrderDetail.setNum(goodsComboNum);
		webOrderDetail.setPrice(webGoodsCombo.getPrice());
		webOrderDetail.setIsHistroy("0");
		webOrderDetailService.save(webOrderDetail);
		orderService.save(Order);
	}
	
	public String getOrderReturnCode(){
		String format = "%02d";
		Date nowDate = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String now = sdf.format(nowDate);
		int OrderCode = getMaxOrderReturnCode(now);
		OrderCode = OrderCode+1;
		String a = now+format;
		return String.format(a, OrderCode);
	}
	
	private int getMaxOrderReturnCode(String now){
		String code = orderService.findMaxCode(now);
		if(code!=null){
			return Integer.parseInt(code.substring(14));
		}else{
			return 0;
		}
	}
}